<template>
  <div>
    <el-upload
    v-show="!hideUpload"
    action=""
    list-type="picture-card"
    :http-request="handleUpload"
    :on-remove="handleRemove"
    :limit="imageLimit"
    :file-list="fileList"
    ref="my-upload"
    >
      <i slot="default" class="el-icon-plus"></i>
  </el-upload>
  <el-dialog :visible.sync="dialogVisible">
    <img width="100%" :src="dialogImageUrl" alt="">
  </el-dialog>
  </div>
</template>

<script>
import {uploadFile} from '@/api/upload';

export default {
  data(){
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      fileList:[],
      urls:[],
      hideUpload: false
    }
  },
  props:{
    imageLimit:{
      type: Number,
      default: 3,
      require: false
    }
  },
  methods: {
    handleRemove(file,fileList) {
      let idx=0
      fileList.filter((cur,index)=>{
        if(cur!==file){
          idx=index
        }
        return cur!==file
      })

      this.urls.splice(idx,1)
      
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    async handleUpload(file){
      let res=await uploadFile(file)
      let url=res.data.data
      this.urls.push({image: url})
    },
    clearUpload(){
      this.$refs['my-upload'].clearFiles()
      this.urls=[]
    },
    initImages(imgs){
      if(typeof imgs==='string'){
        this.urls=[{image: imgs}]
        this.fileList=[{url: imgs}]
        return
      }
      this.fileList=imgs.map((t)=>{
        var obj = {}
        obj.url = t.image
        return obj
      })
      this.urls=imgs
      
    }
  },
  watch:{
    urls(newVal){
      
      this.$emit('handleUpload',newVal)
      const el=this.$refs['my-upload'].$el
      const pc=el.getElementsByClassName('el-upload--picture-card')[0]
      if(newVal.length>=this.imageLimit){
        pc.setAttribute('style', 'display: none;')
      }
      else{
        pc.setAttribute('style', 'display: ;')
      }
    }
  }
}
</script>

<style>

</style>